import logging
import os
from logging.handlers import TimedRotatingFileHandler
import colorlog
from datetime import datetime

# 存储driver实例的全局变量
_driver_instance = None
# 用于防止重复截图的标记
_last_error_screenshot_time = 0
_SCREENSHOT_INTERVAL = 5  # 截图间隔时间（秒）

def set_driver_instance(driver):
    """设置全局driver实例，供截图使用"""
    global _driver_instance
    _driver_instance = driver

def get_driver_instance():
    """获取全局driver实例"""
    global _driver_instance
    return _driver_instance

class ScreenshotOnErrorFilter(logging.Filter):
    """自定义过滤器，在记录ERROR级别日志时自动截图"""
    
    def filter(self, record):
        global _last_error_screenshot_time
        # 当记录的日志级别为ERROR或更高时，尝试截图
        if record.levelno >= logging.ERROR and get_driver_instance():
            current_time = datetime.now().timestamp()
            # 检查距离上次截图的时间间隔，避免频繁截图
            if current_time - _last_error_screenshot_time >= _SCREENSHOT_INTERVAL:
                try:
                    from utils.screenshot_util import capture_screenshot
                    driver = get_driver_instance()
                    # 使用日志消息的一部分作为文件名
                    log_msg_part = record.getMessage()[:30].replace(" ", "_").replace("/", "_").replace(":", "_")
                    # 获取当前测试用例名称（如果可用）
                    test_method_name = getattr(record, 'test_method_name', None) if hasattr(record, 'test_method_name') else None
                    if test_method_name:
                        capture_screenshot(driver, f"{test_method_name}_log_error_{log_msg_part}")
                    else:
                        # 尝试从调用栈获取测试方法名
                        import traceback
                        import re
                        stack = traceback.extract_stack()
                        test_method = None
                        for frame in reversed(stack):
                            if 'test_' in frame.name:
                                test_method = frame.name
                                break
                        if test_method:
                            capture_screenshot(driver, f"{test_method}_log_error_{log_msg_part}")
                        else:
                            capture_screenshot(driver, f"log_error_{log_msg_part}")
                    _last_error_screenshot_time = current_time
                except Exception as e:
                    # 忽略截图过程中的任何错误，以免影响日志记录
                    pass
        return True

def get_logger():
    # 创建logger对象
    logger = logging.getLogger("AppAutomation")
    logger.setLevel(logging.DEBUG)  # 记录DEBUG及以上级别的日志

    # 检查是否已经添加了处理器，避免重复添加
    if logger.handlers:
        return logger

    # 获取项目根目录的绝对路径
    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # 构造日志目录结构（相对于项目根目录）
    today = datetime.now()
    log_dir = os.path.join(project_root, f"logs/{today.year}/{today.month:02d}")
    os.makedirs(log_dir, exist_ok=True)
    
    # 构造日志文件基础名称（不含扩展名）
    base_log_name = os.path.join(log_dir, f"{today.day:02d}")

    # 定义不同日志等级及其对应的颜色与文件后缀
    levels = {
        'DEBUG': ('debug', 'white'),
        'INFO': ('info', 'white'),
        'WARNING': ('warning', 'yellow'),
        'ERROR': ('error', 'red'),
        'CRITICAL': ('critical', 'bold_red')
    }

    # 为每个日志等级创建一个TimedRotatingFileHandler
    for level_name, (suffix, _) in levels.items():
        filename = f"{base_log_name}-{level_name}.log"
        handler = TimedRotatingFileHandler(filename, when='midnight', interval=1, backupCount=3)
        handler.setLevel(getattr(logging, level_name))
        handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        # 添加自定义过滤器
        handler.addFilter(ScreenshotOnErrorFilter())
        logger.addHandler(handler)

    # 控制台输出日志
    console_handler = logging.StreamHandler()

    # 使用colorlog的ColoredFormatter来实现控制台日志的彩色输出
    formatter = colorlog.ColoredFormatter(
        '%(log_color)s%(asctime)s - %(levelname)s - %(message)s',  # 日志格式
        datefmt='%Y-%m-%d %H:%M:%S',  # 日期时间格式
        log_colors={level: color for level, (_, color) in levels.items()}
    )

    console_handler.setFormatter(formatter)
    # 添加自定义过滤器到控制台处理器
    console_handler.addFilter(ScreenshotOnErrorFilter())
    logger.addHandler(console_handler)

    return logger